﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Bussiness.Entity;
using Bussiness.Manager;
using AF_ORM.CORE;
using ComExcel = Microsoft.Office.Interop.Excel;
using System.Collections;
using System.Threading;
namespace DSC
{
    public partial class ucServiceBill : AfUserControl
    {
        private frmSearch frm = null;
        public ucServiceBill()
        {
            InitializeComponent();
            // default data
            txtTuNgay.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0,0,0);
            txtDenNgay.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);

            checkHoTenKH.Checked = true;
            txtTuKhoa.Enabled = true;

            txtTuKhoa.CharacterCasing = CharacterCasing.Upper;
            txtTuSoPhieu.CharacterCasing = CharacterCasing.Upper;
            txtDenSoPhieu.CharacterCasing = CharacterCasing.Upper;
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter) // 
            {
                LoadGridSearch();
                return true;
            }
            if (keyData == Keys.F2) // hien thi form sua
            {
                if (gridResult.SelectedRows.Count > 0)
                {
                    string BillNo = !string.IsNullOrEmpty((string)gridResult["Bill_NO", gridResult.SelectedRows[0].Index].Value) ? (string)gridResult["Bill_NO", gridResult.SelectedRows[0].Index].Value : "";
                    ((Main)this.Parent.Parent.Parent).ShowControl(new ucBill(BillNo), "Sửa phiếu-" + BillNo);
                }
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        private void HandleCheckChange()
        {
            if (checkHoTenKH.Checked == true || checkBienSo.Checked == true || checkSDT.Checked == true)
                txtTuKhoa.Enabled = true;
            else
                txtTuKhoa.Enabled = false;
        }
        private bool ValidateData()
        {
            if (txtDenNgay.Value.CompareTo(txtTuNgay.Value) < 0)
            {
                MessageBox.Show("Từ ngày phải nhỏ hơn đến ngày");
                return false;
            }
            //TimeSpan c = txtDenNgay.Value.Subtract(txtTuNgay.Value);
            //if (txtDenNgay.Value.Year!=1990 && txtTuNgay.Value.Year!=1990 && c.TotalDays>90)
            //{
            //    MessageBox.Show("Chỉ chọn trong khoảng thời gian 3 tháng trở xuống");
            //    return false;
            //}
            return true;
        }
        private void btSearch_Click(object sender, EventArgs e)
        {
            btSearch.UseWaitCursor = true;
            ShowStatusBar("Đang tìm kiếm phiếu dịch vụ");
            Thread mainThread = new Thread(new ThreadStart(LoadGridSearch));
            mainThread.Start();
            tabSearch.SelectedTab = tabPageHoanThanh;
            btSearch.UseWaitCursor = false;
        }

        private void checkHoTenKH_CheckedChanged(object sender, EventArgs e)
        {
            HandleCheckChange();
        }

        private void checkBienSo_CheckedChanged(object sender, EventArgs e)
        {
            HandleCheckChange();
        }

        private void checkSDT_CheckedChanged(object sender, EventArgs e)
        {
            HandleCheckChange();
        }

        private void gridResult_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            //lay id ra
            string BillNo = !string.IsNullOrEmpty((string)gridResult["Bill_NO", e.RowIndex].Value) ? (string)gridResult["Bill_NO", e.RowIndex].Value : "";
            ((Main)this.Parent.Parent.Parent).ShowControl(new ucBill(BillNo), "Sửa phiếu-"+ BillNo);
        }
        private DataTable GetResult()
        {
            if (ValidateData())
            {
                string tenKH = "";
                string bienSo = "";
                string dienThoai = "";
                if (checkHoTenKH.Checked == true)
                    tenKH = txtTuKhoa.Text.Trim();
                else if (checkBienSo.Checked == true)
                    bienSo = txtTuKhoa.Text.Trim();
                else if (checkSDT.Checked == true)
                    dienThoai = txtTuKhoa.Text;
                string tuPhieu = txtTuSoPhieu.Text.Trim();
                string denPhieu = txtDenSoPhieu.Text.Trim();
                DateTime TuNgay = txtTuNgay.Value;
                DateTime DenNgay = txtDenNgay.Value;
                int isFinished = -1;
                return PT_ServiceBillManager.CreateInstant().AdvanceSearch(isFinished,tenKH, bienSo, dienThoai, tuPhieu, denPhieu, TuNgay, DenNgay, 0, 0, 0, 0, "", "", "", false, "", "", -1, -1, -1, -1);
            }
            return null;
        }
        private void LoadGridSearch()
        {
            DataTable dt = GetResult();
            if (dt != null)
            {
                DataView view = dt.DefaultView;
                view.RowFilter = "IsFinished=1";
                this.Invoke((MethodInvoker)delegate
                { 
                    gridResult.DataSource = view.ToTable().Copy();
                });
                
                lbTotalResult.Text = view.ToTable().Rows.Count + " phiếu";
                view.RowFilter = "IsFinished=0";
                gridTemp.DataSource = view.ToTable().Copy();
            }
            this.Invoke((MethodInvoker)delegate{
                EndShowStatusBar();
            });
        }
        private void gridResult_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(e.RowIndex.ToString()+e.ColumnIndex.ToString());
            if (e.RowIndex == -1 && gridResult.Columns[e.ColumnIndex].Name == "CheckDel")
            {
                for (int i = 0; i < gridResult.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridResult.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                ShowStatusBar("Đang xóa phiếu dịch vụ");
                string bills = "";
                if (tabSearch.SelectedTab == tabPageHoanThanh)
                {
                    for (int i = 0; i < gridResult.RowCount; i++)
                    {
                        DataGridViewCheckBoxCell checkSelect = gridResult.Rows[i].Cells["checkDel"] as DataGridViewCheckBoxCell;
                        if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                        {
                            string BillNo = !string.IsNullOrEmpty((string)gridResult["Bill_NO", i].Value) ? (string)gridResult["Bill_NO", i].Value : "";
                            if (BillNo != "")
                            {
                                PT_ServiceBillEntity obj = PT_ServiceBillManager.CreateInstant().GetByBillNo(BillNo);
                                if (obj != null)
                                {
                                    try
                                    {
                                        PT_ToolInBillManager.CreateInstant().DeleteByBillNo(BillNo);
                                        PT_ServiceBillDetailManager.CreateInstant().DeleteByBill_NO(BillNo);
                                        PT_ServiceBillManager.CreateInstant().DeleteByBill_NO(BillNo);
                                        if (!string.IsNullOrEmpty(bills))
                                            bills += ", ";
                                        bills += BillNo;
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                else if(tabSearch.SelectedTab==tabPageTam)
                {
                    for (int i = 0; i < gridTemp.RowCount; i++)
                    {
                        DataGridViewCheckBoxCell checkSelect = gridTemp.Rows[i].Cells["checkDelTemp"] as DataGridViewCheckBoxCell;
                        if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                        {
                            string BillNo = !string.IsNullOrEmpty((string)gridTemp["Bill_NOTemp", i].Value) ? (string)gridTemp["Bill_NOTemp", i].Value : "";
                            if (BillNo != "")
                            {
                                PT_ServiceBillEntity obj = PT_ServiceBillManager.CreateInstant().GetByBillNo(BillNo);
                                if (obj != null)
                                {
                                    try
                                    {
                                        PT_ToolInBillManager.CreateInstant().DeleteByBillNo(BillNo);
                                        PT_ServiceBillDetailManager.CreateInstant().DeleteByBill_NO(BillNo);
                                        PT_ServiceBillManager.CreateInstant().DeleteByBill_NO(BillNo);
                                        if (!string.IsNullOrEmpty(bills))
                                            bills += ", ";
                                        bills += BillNo;
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(bills))
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa phiếu dịch vụ", "Xóa các phiếu sau: " + bills);
                LoadGridSearch();
                EndShowStatusBar();
            }
        }

        private void btExportExcel_Click(object sender, EventArgs e)
        {
            ShowStatusBar("Đang xuất dữ liệu excel");
            Thread t = new Thread(new ThreadStart(ExportExcel));
            t.Start();
        }

        private void ExportExcel()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("STT");
            dt.Columns.Add("Ngay");
            dt.Columns.Add("Gio");
            dt.Columns.Add("Bill_no");
            dt.Columns.Add("CustName");
            dt.Columns.Add("NumberPlate");
            dt.Columns.Add("Phone");
            dt.Columns.Add("Model");
            dt.Columns.Add("RepairedByName");
            dt.Columns.Add("RepairedByName2");

            dt.Columns.Add("ReceivedByName");
            dt.Columns.Add("CashierName");
            dt.Columns.Add("CheckByName");
            dt.Columns.Add("RAP");
            dt.Columns.Add("KTDK");
            dt.Columns.Add("DV_ThuGCN");
            dt.Columns.Add("DV_ChiGCN");
            dt.Columns.Add("DV_LaiGCN");
            dt.Columns.Add("DV_SC_ThucThu");
            dt.Columns.Add("DV_SuaChua_GiamGia_GG");
            dt.Columns.Add("DV_SuaChua_BaoHanh");
            dt.Columns.Add("DV_SuaChua_ThienChi");
            dt.Columns.Add("DV_SuaChua_KhuyenMai");
            dt.Columns.Add("PT_Thu_PTT");
            dt.Columns.Add("PT_Thu_PTN");
            dt.Columns.Add("PT_Thu_Nhot");
            dt.Columns.Add("PT_GiamGia_GG");
            dt.Columns.Add("PT_BaoHanh");
            dt.Columns.Add("PT_ThienChi");
            dt.Columns.Add("PT_KhuyenMai");
            dt.Columns.Add("PT_Thu_PTTM");
            dt.Columns.Add("PT_Chi_PTTM");
            dt.Columns.Add("PT_Lai_PTTM");
            dt.Columns.Add("ThoiGianSua");
            dt.Columns.Add("TotalMoney");

            DataRow dr = null;
            this.Invoke((MethodInvoker)delegate
            {
                if (tabSearch.SelectedTab == tabPageHoanThanh)
                {
                    for (int i = 0; i < gridResult.Rows.Count; i++)
                    {
                        dr = dt.NewRow();
                        dr["STT"] = (i + 1).ToString();
                        dr["Ngay"] = gridResult.Rows[i].Cells["Ngay"].Value.ToString();
                        dr["Gio"] = gridResult.Rows[i].Cells["Gio"].Value.ToString();
                        dr["Bill_no"] = gridResult.Rows[i].Cells["Bill_no"].Value.ToString();
                        dr["CustName"] = gridResult.Rows[i].Cells["CustName"].Value.ToString();
                        dr["NumberPlate"] = gridResult.Rows[i].Cells["NumberPlate"].Value.ToString();
                        dr["Phone"] = gridResult.Rows[i].Cells["Phone"].Value.ToString();
                        dr["Model"] = gridResult.Rows[i].Cells["Model"].Value.ToString();
                        dr["RepairedByName"] = gridResult.Rows[i].Cells["RepairedByName"].Value.ToString();
                        dr["RepairedByName2"] = gridResult.Rows[i].Cells["RepairedByName2"].Value.ToString();
                        dr["ReceivedByName"] = gridResult.Rows[i].Cells["ReceivedByName"].Value.ToString();
                        dr["CashierName"] = gridResult.Rows[i].Cells["CashierName"].Value.ToString();
                        dr["CheckByName"] = gridResult.Rows[i].Cells["CheckByName"].Value.ToString();
                        dr["RAP"] = gridResult.Rows[i].Cells["RAP"].Value.ToString();
                        dr["KTDK"] = gridResult.Rows[i].Cells["KTDK"].Value.ToString();
                        dr["DV_ThuGCN"] = gridResult.Rows[i].Cells["DV_ThuGCN"].Value.ToString();
                        dr["DV_ChiGCN"] = gridResult.Rows[i].Cells["DV_ChiGCN"].Value.ToString();
                        dr["DV_LaiGCN"] = gridResult.Rows[i].Cells["DV_LaiGCN"].Value.ToString();
                        dr["DV_SC_ThucThu"] = gridResult.Rows[i].Cells["DV_SC_ThucThu"].Value.ToString();
                        dr["DV_SuaChua_GiamGia_GG"] = gridResult.Rows[i].Cells["DV_SuaChua_GiamGia_GG"].Value.ToString();
                        dr["DV_SuaChua_BaoHanh"] = gridResult.Rows[i].Cells["DV_SuaChua_BaoHanh"].Value.ToString();
                        dr["DV_SuaChua_ThienChi"] = gridResult.Rows[i].Cells["DV_SuaChua_ThienChi"].Value.ToString();
                        dr["DV_SuaChua_KhuyenMai"] = gridResult.Rows[i].Cells["DV_SuaChua_KhuyenMai"].Value.ToString();
                        dr["PT_Thu_PTT"] = gridResult.Rows[i].Cells["PT_Thu_PTT"].Value.ToString();
                        dr["PT_Thu_PTN"] = gridResult.Rows[i].Cells["PT_Thu_PTN"].Value.ToString();
                        dr["PT_Thu_Nhot"] = gridResult.Rows[i].Cells["PT_Thu_Nhot"].Value.ToString();
                        dr["PT_GiamGia_GG"] = gridResult.Rows[i].Cells["PT_GiamGia_GG"].Value.ToString();
                        dr["PT_BaoHanh"] = gridResult.Rows[i].Cells["PT_BaoHanh"].Value.ToString();
                        dr["PT_ThienChi"] = gridResult.Rows[i].Cells["PT_ThienChi"].Value.ToString();
                        dr["PT_KhuyenMai"] = gridResult.Rows[i].Cells["PT_KhuyenMai"].Value.ToString();
                        dr["PT_Thu_PTTM"] = gridResult.Rows[i].Cells["PT_Thu_PTTM"].Value.ToString();
                        dr["PT_Chi_PTTM"] = gridResult.Rows[i].Cells["PT_Chi_PTTM"].Value.ToString();
                        dr["PT_Lai_PTTM"] = gridResult.Rows[i].Cells["PT_Lai_PTTM"].Value.ToString();
                        dr["ThoiGianSua"] = gridResult.Rows[i].Cells["ThoiGianSua"].Value.ToString();
                        dr["TotalMoney"] = gridResult.Rows[i].Cells["TotalMoney"].Value.ToString();
                        dt.Rows.Add(dr);
                    }
                }
                else
                {
                    for (int i = 0; i < gridTemp.Rows.Count; i++)
                    {
                        dr = dt.NewRow();
                        dr["STT"] = (i + 1).ToString();
                        dr["Ngay"] = gridTemp.Rows[i].Cells["NgayTemp"].Value.ToString();
                        dr["Gio"] = gridTemp.Rows[i].Cells["GioTemp"].Value.ToString();
                        dr["Bill_no"] = gridTemp.Rows[i].Cells["Bill_noTemp"].Value.ToString();
                        dr["CustName"] = gridTemp.Rows[i].Cells["CustNameTemp"].Value.ToString();
                        dr["NumberPlate"] = gridTemp.Rows[i].Cells["NumberPlateTemp"].Value.ToString();
                        dr["Phone"] = gridTemp.Rows[i].Cells["PhoneTemp"].Value.ToString();
                        dr["Model"] = gridTemp.Rows[i].Cells["ModelTemp"].Value.ToString();
                        dr["RepairedByName"] = gridTemp.Rows[i].Cells["RepairedByNameTemp"].Value.ToString();
                        dr["RepairedByName2"] = gridTemp.Rows[i].Cells["RepairedByName2Temp"].Value.ToString();
                        dr["ReceivedByName"] = gridTemp.Rows[i].Cells["ReceivedByNameTemp"].Value.ToString();
                        dr["CashierName"] = gridTemp.Rows[i].Cells["CashierNameTemp"].Value.ToString();
                        dr["CheckByName"] = gridTemp.Rows[i].Cells["CheckByNameTemp"].Value.ToString();
                        dr["RAP"] = gridTemp.Rows[i].Cells["RAPTemp"].Value.ToString();
                        dr["KTDK"] = gridTemp.Rows[i].Cells["KTDKTemp"].Value.ToString();
                        dr["DV_ThuGCN"] = gridTemp.Rows[i].Cells["DV_ThuGCNTemp"].Value.ToString();
                        dr["DV_ChiGCN"] = gridTemp.Rows[i].Cells["DV_ChiGCNTemp"].Value.ToString();
                        dr["DV_LaiGCN"] = gridTemp.Rows[i].Cells["DV_LaiGCNTemp"].Value.ToString();
                        dr["DV_SC_ThucThu"] = gridTemp.Rows[i].Cells["DV_SC_ThucThuTemp"].Value.ToString();
                        dr["DV_SuaChua_GiamGia_GG"] = gridTemp.Rows[i].Cells["DV_SuaChua_GiamGia_GGTemp"].Value.ToString();
                        dr["DV_SuaChua_BaoHanh"] = gridTemp.Rows[i].Cells["DV_SuaChua_BaoHanhTemp"].Value.ToString();
                        dr["DV_SuaChua_ThienChi"] = gridTemp.Rows[i].Cells["DV_SuaChua_ThienChiTemp"].Value.ToString();
                        dr["DV_SuaChua_KhuyenMai"] = gridTemp.Rows[i].Cells["DV_SuaChua_KhuyenMaiTemp"].Value.ToString();
                        dr["PT_Thu_PTT"] = gridTemp.Rows[i].Cells["PT_Thu_PTTTemp"].Value.ToString();
                        dr["PT_Thu_PTN"] = gridTemp.Rows[i].Cells["PT_Thu_PTNTemp"].Value.ToString();
                        dr["PT_Thu_Nhot"] = gridTemp.Rows[i].Cells["PT_Thu_NhotTemp"].Value.ToString();
                        dr["PT_GiamGia_GG"] = gridTemp.Rows[i].Cells["PT_GiamGia_GGTemp"].Value.ToString();
                        dr["PT_BaoHanh"] = gridTemp.Rows[i].Cells["PT_BaoHanhTemp"].Value.ToString();
                        dr["PT_ThienChi"] = gridTemp.Rows[i].Cells["PT_ThienChiTemp"].Value.ToString();
                        dr["PT_KhuyenMai"] = gridTemp.Rows[i].Cells["PT_KhuyenMaiTemp"].Value.ToString();
                        dr["PT_Thu_PTTM"] = gridTemp.Rows[i].Cells["PT_Thu_PTTMTemp"].Value.ToString();
                        dr["PT_Chi_PTTM"] = gridTemp.Rows[i].Cells["PT_Chi_PTTMTemp"].Value.ToString();
                        dr["PT_Lai_PTTM"] = gridTemp.Rows[i].Cells["PT_Lai_PTTMTemp"].Value.ToString();
                        dr["ThoiGianSua"] = gridTemp.Rows[i].Cells["ThoiGianSuaTemp"].Value.ToString();
                        dr["TotalMoney"] = gridTemp.Rows[i].Cells["TotalMoneyTemp"].Value.ToString();
                        dt.Rows.Add(dr);
                    }
                }
                saveFileExcel.FileName = "PhieuDichVu_" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm") + ".xls";
                saveFileExcel.DefaultExt = "xls";
                saveFileExcel.Filter = "Excel 2003 Files(*.xls)|*.xls|Excel 2007(*.xlsx)|*.xlsx|All Files|*.*";
                saveFileExcel.AddExtension = true;
                saveFileExcel.RestoreDirectory = true;
                saveFileExcel.Title = "Chọn đường dẫn lưu file";
                saveFileExcel.InitialDirectory = @"C:/";
                if (saveFileExcel.ShowDialog() == DialogResult.OK)
                {
                    if (saveFileExcel.FileName.Split('\\')[saveFileExcel.FileName.Split('\\').Length - 1] == ".xls")
                    {
                        MessageBox.Show("Nhập tên file cần lưu");
                    }
                    else
                    {
                        // Khoi dong Excel
                        ComExcel.Application exApp = new ComExcel.Application();

                        //// them file temp xls moi
                        //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);

                        // Mo mot file Excel co san
                        //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);
                        ComExcel.Workbook exBook = exApp.Workbooks.Add(Application.StartupPath + "/ExcelTemplate/MauKhungSearch.xls");

                        // Lay sheet 1
                        ComExcel.Worksheet exSheet = (ComExcel.Worksheet)exBook.Worksheets[1];
                        //exSheet.Activate();

                        ////cau hình chung
                        //ComExcel.Range rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[8, 1], exSheet.Cells[8 + dt.Rows.Count, HondaTypeList.Count]);
                        //rng.Interior.Pattern = ComExcel.Constants.xlSolid;
                        //rng.Borders.LineStyle = ComExcel.XlLineStyle.xlContinuous;
                        //rng.VerticalAlignment = ComExcel.XlVAlign.xlVAlignCenter;
                        //rng.HorizontalAlignment = ComExcel.XlHAlign.xlHAlignCenter;
                        ComExcel.Range rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[5, 1], exSheet.Cells[1000, 35]);
                        rng.Font.Size = 9;
                        rng.WrapText = true;
                        // đổ dữ liệu
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[5 + i, 1], exSheet.Cells[5 + i, 35]);
                            rng.Interior.Pattern = ComExcel.Constants.xlSolid;
                            rng.Borders.LineStyle = ComExcel.XlLineStyle.xlContinuous;
                            rng.VerticalAlignment = ComExcel.XlVAlign.xlVAlignCenter;
                            rng.HorizontalAlignment = ComExcel.XlHAlign.xlHAlignCenter;

                            for (int j = 0; j < dt.Columns.Count; j++)
                            {
                                exSheet.Cells[5 + i, j + 1] = dt.Rows[i][j].ToString();
                            }
                        }

                        exBook.SaveAs(saveFileExcel.FileName, ComExcel.XlFileFormat.xlWorkbookNormal, null, null, false, false, ComExcel.XlSaveAsAccessMode.xlExclusive, false, false, false, false, false);
                        DialogResult dlg = MessageBox.Show("File Excel được lưu ở đường dẫn sau: " + saveFileExcel.FileName + Environment.NewLine + "Bạn có muốn mở file không ?", "Thông Báo", MessageBoxButtons.YesNo);
                        if (dlg == DialogResult.Yes)
                        {
                            // hien thi chuong trinh excel
                            exApp.Visible = true;
                            exBook.ReadOnlyRecommended = false;
                        }
                        else
                        {
                            exBook.Close(false, false, false);
                            exApp.Quit();
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
                        }
                    }
                }
            });
            this.Invoke((MethodInvoker)delegate
            {
                EndShowStatusBar();
            });
        }
        public void AdvanceSearch(object param)
        {
            ShowStatusBar("Đang tìm kiếm phiếu dịch vụ");
            Thread t = new Thread(new ParameterizedThreadStart(RunAdvanceSearch));
            t.Start(param);
            //RunAdvanceSearch(isFinished, tenKH, bienSo, dienThoai, tuPhieu, denPhieu, ref tuNgay, ref denNgay, nvSuaChua, nvTiepNhan, nvKiemTra, nvThuNgan, lstDichVu, lstGiamGiaDichVu, lstPhuTung, isOil, lstGiamGiaPhuTung, lstPhanLoaiXe, tongTienTu, tongTienDen, phutThucHienTu, phutThucHienDen);
        }

        private void RunAdvanceSearch(object param)
        {
            object[] temp = (object[])param;
            int isFinished = (int)temp[0];
            string tenKH = (string)temp[1];
            string bienSo = (string)temp[2];
            string dienThoai = (string)temp[3];
            string tuPhieu = (string)temp[4];
            string denPhieu = (string)temp[5];
            DateTime tuNgay = (DateTime)temp[6];
            DateTime denNgay = (DateTime)temp[7];
            int nvSuaChua = (int)temp[8];
            int nvTiepNhan = (int)temp[9];
            int nvKiemTra = (int)temp[10];
            int nvThuNgan = (int)temp[11];
            string lstDichVu = (string)temp[12];
            string lstGiamGiaDichVu = (string)temp[13];
            string lstPhuTung = (string)temp[14];
            bool isOil = (bool)temp[15];
            string lstGiamGiaPhuTung = (string)temp[16];
            string lstPhanLoaiXe = (string)temp[17];
            decimal tongTienTu = (decimal)temp[18];
            decimal tongTienDen = (decimal)temp[19];
            int phutThucHienTu = (int)temp[20];
            int phutThucHienDen = (int)temp[21];
            //int isFinished, string tenKH, string bienSo, string dienThoai, string tuPhieu, string denPhieu, ref DateTime tuNgay, ref DateTime denNgay, int nvSuaChua, int nvTiepNhan, int nvKiemTra, int nvThuNgan, string lstDichVu, string lstGiamGiaDichVu, string lstPhuTung, bool isOil, string lstGiamGiaPhuTung, string lstPhanLoaiXe, decimal tongTienTu, decimal tongTienDen, int phutThucHienTu, int phutThucHienDen
            DataTable dt = PT_ServiceBillManager.CreateInstant().AdvanceSearch(isFinished, tenKH, bienSo, dienThoai, tuPhieu, denPhieu, tuNgay, denNgay, nvSuaChua, nvTiepNhan, nvKiemTra, nvThuNgan, lstDichVu, lstGiamGiaDichVu, lstPhuTung, isOil, lstGiamGiaPhuTung, lstPhanLoaiXe, tongTienTu, tongTienDen, phutThucHienTu, phutThucHienDen);
            DataView view = dt.DefaultView;
            view.RowFilter = "IsFinished=1";
            this.Invoke((MethodInvoker)delegate
            {
                gridResult.DataSource = view.ToTable().Copy();
                lbTotalResult.Text = view.ToTable().Rows.Count + " phiếu";

                view.RowFilter = "IsFinished=0";
                gridTemp.DataSource = view.ToTable().Copy();

                tabSearch.SelectedTab = tabPageHoanThanh;
                EndShowStatusBar();
            });
            
        }
        private void btAdvanceSearch_Click(object sender, EventArgs e)
        {
            if (frm == null)
            {
                frm = new frmSearch(); 
            }
            frm.advanceSearch = new frmSearch.AdvanceSearch(AdvanceSearch);
            frm.Show();
        }
        private void closeAdvanceSearchForm()
        {
            frm = null;
        }

        private void kryptonTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabSearch.SelectedTab == tabPageHoanThanh)
                lbTotalResult.Text = gridResult.RowCount + " phiếu";
            else
                lbTotalResult.Text = gridTemp.RowCount + " phiếu";
        }

        private void gridTemp_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(e.RowIndex.ToString()+e.ColumnIndex.ToString());
            if (e.RowIndex == -1 && gridTemp.Columns[e.ColumnIndex].Name == "CheckDelTemp")
            {
                for (int i = 0; i < gridTemp.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridTemp.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void gridTemp_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            ShowStatusBar("Đang load phiếu dịch vụ");
            if (e.RowIndex < 0)
                return;
            //lay id ra
            string BillNo = !string.IsNullOrEmpty((string)gridTemp["Bill_NOTemp", e.RowIndex].Value) ? (string)gridTemp["Bill_NOTemp", e.RowIndex].Value : "";
            ((Main)this.Parent.Parent.Parent).ShowControl(new ucBill(BillNo), "Sửa phiếu-" + BillNo);
            EndShowStatusBar();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(LoadGridSearch));
            t.IsBackground = true;
            t.Start();
            ShowStatusBar("Đang tìm kiếm phiếu dịch vụ");
            //LoadGridSearch();
            //tabSearch.SelectedTab = tabPageHoanThanh;
            EndShowStatusBar();
        }
    }
}
